﻿var NamChitieu = function () {
    function Loadtree(select, value) {
        $(select).empty();
        var flagcap1 = 0;
        var flagcap2 = 0;
        $.each(value, function (i, v) {
            if (v.CAP == '1') {
                flagcap1 = v.MA_CAP1;
                $(select).append('<div class="panel panel-default">\
                    <div class="panel-heading">' + v.TEN_CHI_TIEU_CAP1 + '</div>\
                    <div class="panel-body body-'+ v.MA_CAP1 + ' ">\
                    </div>\
                </div>\
                            ');
            }
            if (v.CAP == '2') {
                if (v.MA_CAP1 == flagcap1) {
                    $('.body-' + v.MA_CAP1 + '').append('\
                                <span class="span-' + v.MA_CAP2 + ' ">+</span>\
                                <input type="checkbox" class="checkvaluecha cap-' + v.MA_CAP2 + '"  level="2" value="' + v.MA_CAP2 + '" />\
                        <span class="showdetail tencap2-' + v.MA_CAP2 + '" data="' + v.MA_CAP2 + '">' + v.TEN_CHI_TIEU_CAP2 + '</span>\
                        <ul >\
                            <div class="tencap3-' + v.MA_CAP2 + '" style="display:none;" >\
                            </div>\
                        </ul>\
                                ');
                    flagcap2 = v.MA_CAP2;
                }
            }
            if (v.CAP == '3') {
                if (v.MA_CAP2 == flagcap2) {
                    $('.tencap3-' + v.MA_CAP2 + '').append('<li>\
                                        <input type="checkbox"  class="checkvaluecon check-'+ v.MA_CAP2 + '" level="3" data-cha="' + v.MA_CAP2 + '" value="' + v.CHI_TIEU_ID + '"/>\
                                    <span>'+ v.TEN_CHI_TIEU_CAP3 + '</span>\
                                    </li>\
                                ');
                }
            }
        })
    }
    function getrowspan(value, data) {
        var kq = 1;
        $.each(data, function (i, v) {
            if (v.CAP == 3 && v.MA_CAP2 == value) {
                kq += 1;
            }
        })
        return kq;
    }
    function calculateSum(a) {
        var sum = 0;
        //iterate through each textboxes and add the values
        $(".restartall").each(function () {
            if ($(this).attr('name') == a) {
                //add only if the value is number
                if (!isNaN(this.value) && this.value.length != 0) {
                    sum += parseFloat(this.value);
                }
            }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places
        $('.' + a + '').val(sum);
    }
    function calculateSumrestart(a) {
        var sum = 0;
        //iterate through each textboxes and add the values
        $(".restart").each(function () {
            if ($(this).attr('name') == a) {
                //add only if the value is number
                if (!isNaN(this.value) && this.value.length != 0) {
                    sum += parseFloat(this.value);
                }
            }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places
        $('.' + a + '').val(sum);
    }
    var initLoadData = function (initData) {
        $.ajax({
            url: initData.GetDonViByNhom,
            type: "GET",
            headers: {
                'VerificationToken': initData.VerificationToken
            },
            dataType: "json",
            async: false,
            data: {
                'status': true
            },
            success: function (data) {
                var lstDonvi = '<option value="-1">[--Chọn đơn vị--]</option>';
                $.each(data, function (i, v) {
                    lstDonvi += ('<option value="' + v.DonViId + '">' + v.TenVietTat + '</option>');
                });
                $.session.set('lstDonvi', lstDonvi);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                window.notice('Có lỗi xảy ra trong quá trình lưu thông tin: ' + errorThrown, window.notice_error);
            },
            complete: function () {
            }
        });
        $.ajax({
            url: initData.GetallChitieu,
            type: "GET",
            headers: {
                'VerificationToken': initData.VerificationToken
            },
            dataType: "json",
            success: function (data) {
                Loadtree('.noidung', data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                window.notice('Có lỗi xảy ra trong quá trình lưu thông tin: ' + errorThrown, window.notice_error);
            },
            complete: function () {

            }
        });
        $.ajax({
            url: initData.GetallNamkehoach,
            type: "GET",
            headers: {
                'VerificationToken': initData.VerificationToken
            },
            dataType: "json",
            success: function (data) {
                $('#Namkehoach').empty();
                $('#Namkehoach').append('<option value="-1">[--Chọn năm kế hoạch--]</option>');
                $.each(data, function (i, v) {
                    $('#Namkehoach').append('<option value="' + v.NAM_KE_HOACH_ID + '">' + v.NAM_KE_HOACH + '</option>');
                })
                var namkh = $.cookie('mkhidchung');
                if (namkh != undefined) {
                    $('#Namkehoach').val(namkh);
                    if ($('#Namkehoach').val() != '-1') {
                        var namnay = $('#Namkehoach option:selected').text();
                        $('.namtruoc').text((namnay - 1));
                        $('.namsau').text((namnay));
                    }
                    
                    Loadtable(namkh, initData);
                }
                
            },
            error: function (jqXHR, textStatus, errorThrown) {
                window.notice('Có lỗi xảy ra trong quá trình lưu thông tin: ' + errorThrown, window.notice_error);
            },
            complete: function () {
            }
        });
        var chitieuid = [];
        $.session.set('chitieuid', chitieuid);
    };
    function Loadtable(namkehoachid, initData) {
        var chitieuid = [];
        $.ajax({
            url: initData.GetallChitieubynamchitieu,
            type: "GET",
            headers: {
                'VerificationToken': initData.VerificationToken
            },
            dataType: "json",
            data: {
                'namchitieuid': namkehoachid,
                'madonvi':0
            },
            success: function (data) {
                var stt1 = 0;
                var stt2 = 0;
                var stt3 = 1;
                $('tbody').empty();
                $.each(data, function (i, v) {
                    if (v.CAP == 1) {
                        $('tbody').append('<tr>\
                                        <td colspan="7" style="text-align: left;font-weight: bold;">\
                                         '+ v.TEN_CHI_TIEU + '\
                                     </td>\
                                 </tr>');
                    }
                    if (v.CAP == 2) {
                        stt1 += 1;
                        stt2 = 0;
                        $('tbody').append('<tr>\
                                    <td rowspan="'+ getrowspan(v.MA_CAP2, data) + '">' + stt1 + '</td>\
                                        <td></td>\
                                        <td style="text-align: left;font-weight: bold;">'+ v.TEN_CHI_TIEU + '</td>\
                                        <td><select class="form-control bancha" level="2" chitieuid="'+v.CHI_TIEU_ID+'"  data="' + v.MA_CAP2 + '" >' + $.session.get('lstDonvi') + '</select></td>\
                                        <td>' + v.DON_VI_TINH + '</td>\
                                        <td><span><input type="text"  class="e-input1 form-control before bd'+stt1+'" ctid="' + v.CHI_TIEU_ID + '" disabled="disabled" /></span></td>\
                                        <td><span><input data="' + v.MA_CAP2 + '" type="text" chieutieuid="' + v.CHI_TIEU_ID + '" donviid="-1" disabled="disabled" class="e-input2 form-control cd' + stt1 + ' kehoach restartall " /></span></td>\
                                    </tr>');
                    }
                    if (v.CAP == 3) {
                        chitieuid.push(v.CHI_TIEU_ID);
                        stt2 += 1;
                        $('tbody').append('<tr>\
                                   <td>'+ stt1 + '.' + stt2 + '</td>\
                                       <td style="text-align: left;">'+ v.TEN_CHI_TIEU + '</td>\
                                        <td><select class="form-control bancon" level="3" data="'+v.MA_CAP3+'" data-cha="'+v.MA_CAP2+'" chitieuid="' + v.CHI_TIEU_ID + '" >' + $.session.get('lstDonvi') + '</select></td>\
                                      <td>' + v.DON_VI_TINH + '</td>\
                                         <td><span><input type="text" class="e-input1 form-control before restart" name="bd' + stt1 + '" disabled="disabled" ctid="' + v.CHI_TIEU_ID + '"  /></span></td>\
                                    <td><span><input type="text" data="' + v.MA_CAP3 + '" name="cd' + stt1 + '" data-cha="' + v.MA_CAP2 + '" tabindex="'+stt3+'" chieutieuid="' + v.CHI_TIEU_ID + '" donviid="-1" class="e-input2 form-control kehoach restartall" /></span></td>\
                                </tr>');
                        stt3 += 1;
                    }
                });
                $.session.set('chitieuid', chitieuid);
                
                $.ajax({
                    url: initData.GetKehoachbyNamkehoach,
                    type: "GET",
                    headers: {
                        'VerificationToken': initData.VerificationToken
                    },
                    dataType: "json",
                    data: {
                        'namkhid': namkehoachid,
                        'statusid': 0,
                        'flag':1
                    },
                    success: function (data) {
                        $.each(data, function (i, v) {
                            $('input[ctid="' + v.CHI_TIEU_ID + '"]').val(v.GIA_TRI);
                        });
                        $.ajax({
                            url: initData.GetKehoachbyNamkehoach,
                            type: "GET",
                            headers: {
                                'VerificationToken': initData.VerificationToken
                            },
                            dataType: "json",
                            data: {
                                'namkhid': namkehoachid,
                                'statusid': 0,
                                'flag': 0
                            },
                            success: function (data) {
                                $.each(data, function (i, v) {
                                    $('select[chitieuid="' + v.CHI_TIEU_ID + '"]').val(v.DON_VI_ID);
                                    $('input[chieutieuid="' + v.CHI_TIEU_ID + '"]').val(v.GIA_TRI);
                                    $('input[chieutieuid="' + v.CHI_TIEU_ID + '"]').attr('donviid', v.DON_VI_ID);
                                });
                                //$('.restartall').blur(function () {
                                //    if ($(this).val() != "") {
                                //        alert($(this).val());
                                //        if (!isNumeric($(this).val())) {
                                //            alert('Bạn vui lòng nhập kiểu số !');
                                //            $(this).val('');
                                //        }
                                //    }
                                //});
                                $(".restartall").each(function () {
                                    var b = $(this).attr('name');
                                    calculateSum(b);
                                    $(this).keyup(function () {
                                        var a = $(this).attr('name');
                                        calculateSum(a);
                                    });
                                });
                                $(".restart").each(function () {
                                    var b = $(this).attr('name');
                                    calculateSumrestart(b);
                                    $(this).keyup(function () {
                                        var fd = $(this).attr('name');
                                        calculateSumrestart(fd);
                                    });
                                });
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                window.notice('Có lỗi xảy ra trong quá trình lưu thông tin: ' + errorThrown, window.notice_error);
                            },
                            complete: function () {

                            }
                        });
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        window.notice('Có lỗi xảy ra trong quá trình lưu thông tin: ' + errorThrown, window.notice_error);
                    },
                    complete: function () {

                    }
                });
            },
            error: function (jqXHR, textStatus, errorThrown) {
                window.notice('Có lỗi xảy ra trong quá trình lưu thông tin: ' + errorThrown, window.notice_error);
            },
            complete: function () {

            }
        });
    }
    var initButtonClick = function (initData) {
        $('#Taomoi').on('click', function () {
            $('#myModal').modal('show');
            $('.noidung input[level="3"]').each(function () {
                $(this).prop('checked', false);
            });
            $('.noidung input[level="2"]').each(function () {
                $(this).prop('checked', false);
                $(this).prop("indeterminate", false);
            });
            var a = $.session.get('chitieuid');
            var mtp = a.split(',');
            if (mtp.length > 0) {
                for (i = 0; i < mtp.length; i++) {
                    $('.noidung input[level="3"]').each(function () {
                        if ($(this).val() == mtp[i]) {
                            var datacha = $(this).attr('data-cha');
                            $('.cap-' + datacha + '').prop("indeterminate", true);
                            $(this).prop('checked', true);
                        }
                    });
                }
            }
        });
        $('.showdetail').live('click', function () {
            var a = $(this).attr('data');
            if ($('.tencap3-' + a + '').css('display') == 'none') {
                $('.tencap3-' + a + '').show();
                $('.span-' + a + '').text('-');
            } else {
                $('.tencap3-' + a + '').hide();
                $('.span-' + a + '').text('+');
            }

        });
        $('.checkvaluecha').live('click', function () {

            var a = $(this).val();
            if ($(this).is(':checked')) {
                $('.check-' + a + '').prop("checked", true);
            } else {
                $('.check-' + a + '').prop("checked", false);
            }
        })
        $('.checkvaluecon').live('click', function () {
            var a = $(this).attr('data-cha');
            var lg = $('.check-' + a + '').length;

            if ($('.cap-' + a + '').is(':checked')) {
                $('.cap-' + a + '').prop("checked", false);
                $('.cap-' + a + '').prop("indeterminate", true);
            }
            if ($(this).is(':checked')) {
                if ($('.check-' + a + '').is(':checked').length == lg) {
                    $('.cap-' + a + '').prop("indeterminate", false);
                    $('.cap-' + a + '').prop("checked", true);
                }
                $('.cap-' + a + '').prop("indeterminate", true);
            }

        })
        $('#Update').live('click', function () {
            var selected = [];
            $('.noidung input[level="3"]').each(function () {
                if ($(this).is(":checked")) {
                    selected.push($(this).val());
                }
            });
            $.ajax({
                url: initData.SaveNamChitieu,
                type: "POST",
                traditional: true,
                headers: {
                    'VerificationToken': initData.VerificationToken
                },
                dataType: "json",
                data: {
                    'namkehoachid': $('#Namkehoach').val(),
                    'listchitieu': selected
                },
                success: function (data) {
                    Loadtable($('#Namkehoach').val(), initData)
                    $('#myModal').modal('hide');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    window.notice('Có lỗi xảy ra trong quá trình lưu thông tin: ' + errorThrown, window.notice_error);
                },
                complete: function () {

                }
            });
        })
        $('#Namkehoach').on('change', function () {
            var namekehoach = $(this).val();
            if (namekehoach != '-1') {
               
            } else {

            }
            if ($('#Namkehoach').val() != '-1') {
                var namnay = $('#Namkehoach option:selected').text();
                $('.namtruoc').text((namnay - 1));
                $('.namsau').text((namnay));
            }
            $.session.set('namkehoachchung', namekehoach);
            $.cookie('mkhidchung', namekehoach);
            Loadtable(namekehoach, initData);

        })
        $('.bancha').live('change', function () {
            var cha = $(this).attr('data');
            var vl = $(this).val();
            $('tbody select[data-cha="' + cha + '"]').each(function () {
                $(this).val(vl);
            });
            $('tbody input[data-cha="' + cha + '"]').each(function () {
                $(this).attr('donviid', vl);
            });
            $('tbody input[data="' + cha + '"]').attr('donviid', vl);
        })
        $('.bancon').live('change', function () {
            var cha = $(this).attr('data');
            var vl = $(this).val();
            $('tbody input[data="' + cha + '"]').attr('donviid', vl);
        })
        $('#Ghinhan').on('click', function () {
            var lstdonvichitieu = [];
            var lstkehoach = [];
            var date = new Date();
            var time = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
            $('tbody select[level="3"]').each(function () {
                if ($(this).val() != "-1") {
                    var obj = {
                        'DON_VI_CHI_TIEU_ID': 0,
                        'DON_VI_ID': $(this).val(),
                        'CHI_TIEU_ID': $(this).attr('chitieuid'),
                        'NAM_KE_HOACH_ID': $('#Namkehoach').val(),
                        'FLAG':1
                    }
                    lstdonvichitieu.push(obj)
                }
            });
            $('tbody .kehoach').each(function (i,v) {
                var obj = {
                    'ID': 0,
                    'NAM_KE_HOACH_ID': $('#Namkehoach').val(),
                    'DON_VI_ID': $(this).attr('donviid'),
                    'CHI_TIEU_ID': $(this).attr('chieutieuid'),
                    'GIA_TRI': $(this).val(),
                    'STATUS_ID': 0,
                    'IS_CURRENT': 0,
                    'NGUOI_DUNG_ID': 1,
                    'STATUS_DATE':time
                }
                lstkehoach.push(obj);
            });
            $.ajax({
                url: initData.SaveDonViChiTieu,
                type: "POST",
                headers: {
                    'VerificationToken': initData.VerificationToken
                },
                dataType: "json",
                async:false,
                data: JSON.stringify({
                    'modelObj': lstdonvichitieu,
                    'lstkh': lstkehoach,
                    'flag': 1,
                    'statusid': 0,
                    'nhomchitieu': -1,
                    'nhomdonvi': -1,
                    'chot':0
                }),
                contentType: 'application/json',
                success: function (data) {
                    window.notice(data, window.notice_success);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    window.notice('Có lỗi xảy ra trong quá trình lưu thông tin: ' + errorThrown, window.notice_error);
                },
                complete: function () {

                }
            });


        })
    };
    return {
        init: function (initData) {
            //load data
            initLoadData(initData);
            initButtonClick(initData);
        }
    }
}();